'use strict';
const Controller = require('egg').Controller;
class ClazzController extends Controller {
  // restful: index/create/destroy/update
  // 不做任何异常处理

  // 班级、学生

  // 查
  async showById() {
    try {
      const id = this.ctx.request.query.id;
      const singleClazz = await this.app.model.Clazz.findAll({
        where: {
          id,
        },
      });
      this.ctx.body = this.ctx.response._success(singleClazz);
    } catch (error) {
      this.ctx.body = this.ctx.response._lack();
    }

  }
  async Allshow() {
    try {
      const list = await this.app.model.Clazz.findAll();
      this.ctx.body = this.ctx.response._success(list);
    } catch (error) {
      this.ctx.body = this.ctx.response._error();
    }
  }
  // 增
  async create() {
    const data = this.ctx.request.body;
    const name = this.ctx.request.body.name;
    try {
      await this.app.model.Clazz.create({
        name,
      });
      this.ctx.body = this.ctx.response._success(data);
    } catch (error) {
      this.ctx.body = this.ctx.response._error();
    }
  }
  // 删
  async destory() {
    const id = this.ctx.params.id;
    // console.log(id);
    try {
      await this.app.model.Clazz.destroy({

        where: {
          id,
        },
      });
      this.ctx.body = this.ctx.response._success('成功删除');
    } catch (error) {
      console.log(error);
      this.ctx.body = this.ctx.response._error();
    }
  }
  // 改
  async update() {
    const id = this.ctx.params.id;
    const data = this.ctx.body;
    const name = this.ctx.request.body.name;
    try {
      await this.app.model.Clazz.update({ name }, { where: { id } });
      this.ctx.body = this.ctx.response._success(data);
    } catch (error) {
      this.ctx.body = this.ctx.response._error('修改失败');
    }

  }
}
module.exports = ClazzController;
